<template>
  <div @scroll="target" ref="targetDom" class="maxbox">
    <!-- 回到顶部组件 -->
    <!-- <top-g-o></top-g-o> -->
    <!-- 头部 -->
    <app-header></app-header>
    <!-- 导航 -->
    <keep-alive>
      <app-tap @tapChange="tapChange"></app-tap>
    </keep-alive>
    <!-- 内容展示 -->
    <keep-alive>
      <app-list @detailsChange="detailsChange" :obj="obj"></app-list>
    </keep-alive>

    <div @click="goTop" v-if="backFlag" class="scrollTop">
      回到顶部
    </div>
  </div>
</template>

<script>
import AppHeader from "../components/appHeader.vue";
import AppList from "../components/appList.vue";
import AppTap from "../components/appTap.vue";
import { ref, watch } from "vue";
import { getList, getDetails } from "../request.js";
import TopGO from "../components/topGO.vue";
export default {
  setup() {
    let obj = ref([]);
    let backFlag = ref(false);
    let targetDom = ref(null);
    if (sessionStorage.getItem("obj")) {
      obj.value = JSON.parse(sessionStorage.getItem("obj"));
    } else {
      console.log(1);
      getList().then(({ data }) => {
        obj.value = data.data;
        sessionStorage.setItem("obj", JSON.stringify(data.data));
      });
    }

    function tapChange(i) {
      // 切换存储数据
      getList(i.id).then(({ data }) => {
        obj.value = data.data;
        console.log(data.data);
        sessionStorage.setItem("obj", JSON.stringify(data.data));
      });
    }

    function target(e) {
      if (e.target.scrollTop > 300) {
        backFlag.value = true;
      } else {
        backFlag.value = false;
      }
      console.log(e.target.scrollTop);
      // if (e.target.scrollTop == 0) {
      //   console.log("小于1了");
      //   clearInterval(clearTime);
      // }
    }

    function detailsChange(i) {
      console.log(i.id);
      getDetails(i.id).then((res) => {
        console.log(res);
      });
    }
    // var clearTime;
    function goTop() {
      // clearTime = setInterval(() => {
      //   targetDom.value.scrollTop -= 20;
      // }, 10);

      let num = targetDom.value.scrollTop;
      // console.log(num);
      //  data.dom.scrollTop = 0;
      let clear = setInterval(() => {
        if (num < 0) {
          clearInterval(clear); // 清除定时器
          return;
        } else {
          num = num - 10;
        }
        // 在最后重新赋值 每次 - 10 的值
        targetDom.value.scrollTop = num;
      }, 15);
    }

    return {
      obj,
      tapChange,
      target,
      backFlag,
      detailsChange,
      goTop,
      targetDom,
    };
  },
  components: { AppHeader, AppTap, AppList, TopGO },
};
</script>

<style lang="scss" scoped>
.maxbox {
  width: 100%;
  height: 100vh;
  overflow-y: scroll;
}
.scrollTop {
  width: 20px;
  height: 100px;
  background-color: red;
  position: fixed;
  bottom: 20px;
  right: 20px;
}
</style>
